﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LeetCodeSolutions
{
    /// <summary>
    /// 28.实现strStr()
    /// </summary>
    class LeetCode28: LeetCodeBase
    {
        public override void Execute()
        {
            CommonFuntions.Print(StrStr("hello", "ll"));
        }

        public int StrStr(string haystack, string needle)
        {
            if (string.IsNullOrEmpty(haystack) && string.IsNullOrEmpty(needle))
            {
                return 0;
            }

            if (string.IsNullOrEmpty(haystack))
            {
                return -1;
            }

            if (string.IsNullOrEmpty(needle))
            {
                return 0;
            }

            int forLength = haystack.Length - needle.Length;

            if (forLength < 0)
            {
                return -1;
            }

            if (haystack == needle)
            {
                return 0;
            }

            int sameLength = 0;
            for (int i = 0; i < forLength + 1; i++)
            {
                sameLength = 0;
                for (int j = 0; j < needle.Length; j++)
                {
                    CommonFuntions.Print(string.Format("haystack[{0}]:{1} needle[{2}]:{3}", j + i, haystack[j + i], j, needle[j]));
                    if (needle[j] != haystack[j + i])
                    {
                        sameLength = 0;
                        //continue;
                    }
                    else
                    {
                        sameLength++;
                    }
                }
                CommonFuntions.Print("length " + sameLength);
                if (sameLength == needle.Length)
                {
                    CommonFuntions.Print("Find");
                    return i;
                }
            }

            CommonFuntions.Print("Final");
            return -1;
        }
    }
}
